const config = require('../config').wechat;
const crypto = require('crypto')
const request = require('request');

const api = {
    production: {
        createOrder: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
        reqOrder: 'https://api.mch.weixin.qq.com/pay/orderquery',
        refund: 'https://api.mch.weixin.qq.com/secapi/pay/refund',
        refundQuery: 'https://api.mch.weixin.qq.com/pay/refundquery',
        downloadbill: 'https://api.mch.weixin.qq.com/pay/downloadbill',
        coupons: 'https://api.mch.weixin.qq.com/mmpaymkttransfers/send_coupon'
    },
    test: {
        sandbox: 'https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey',
        createOrder: 'https://api.mch.weixin.qq.com/sandboxnew/pay/unifiedorder',
        reqOrder: 'https://api.mch.weixin.qq.com/sandboxnew/pay/orderquery',
        refund: 'https://api.mch.weixin.qq.com/sandboxnew/secapi/pay/refund',
        refundQuery: 'https://api.mch.weixin.qq.com/sandboxnew/pay/refundquery',
        downloadbill: 'https://api.mch.weixin.qq.com/sandboxnew/pay/downloadbill'
    },
    codefix: 'https://api.weixin.qq.com/sns/jscode2session?'
}

//新建订单所需方法
////////////////////////////////////////

let js2xml = function (obj) {
    let xmlStr = '<xml>\n'
    for (let key in obj) {
        let aLine = `<${key}>${obj[key]}</${key}>\n`
        xmlStr += aLine
    }
    xmlStr += '</xml>'
    return xmlStr
}

createNonce = function () {
    return Math.random().toString(36).substr(2, 15) + Math.random().toString(36).substr(2, 15)
}

_sign = function (obj) {
    let params = []
    for (let key in obj) {
        let aLine = key + '=' + obj[key]
        params.push(aLine)
    }
    let strA = params.sort().join('&')
    let stringSignTemp = strA + `&key=${config.apiCert}`
    return MD5(stringSignTemp).toUpperCase()
}

function MD5(str) {
    let md5sum = crypto.createHash('md5')
    md5sum.update(str)
    str = md5sum.digest('hex')
    return str
}

//////////////////////////////////////////
//新建统一订单

function createUnifiedOrder (out_trade_no,body, total_fee, spbill_create_ip, trade_type, openid, other) {
    return new Promise((resolve, reject) => {
        let obj = {
            appid: config.appID,
            mch_id: config.mch_id,
            notify_url: config.notify_url,
            body: body,
            out_trade_no: out_trade_no,
            total_fee: total_fee,
            spbill_create_ip: spbill_create_ip,
            trade_type: trade_type,
            openid: openid,
            nonce_str: createNonce(),
            sign_type: 'MD5',
            time_start: other.time_start,
            time_expire: other.time_expire,
        }

        let signStr = this._sign(obj)
        obj.sign = signStr
        let xml = js2xml(obj)

        request({ method: 'POST', url: api.production.createOrder, body: xml, xml: true },function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body)
            }
        })
    })
}

module.exports = createUnifiedOrder